import requests

def fetch_url(url, timeout=5):
    try:
        # 发送 GET 请求
        response = requests.get(url, timeout=timeout)
        
        # 检查 HTTP 状态码
        response.raise_for_status()
        
        # 根据 Content-Type 处理不同格式的响应
        content_type = response.headers.get('Content-Type', '')
        
        if 'application/json' in content_type:
            data = response.json()
            print("JSON 响应数据：")
            print(f"响应包含 {len(data)} 条记录")  # 示例处理
            return data
        elif 'text/html' in content_type:
            print("HTML 响应内容（截取前 200 字符）：")
            print(response.text[:200])
            return response.text
        else:
            print("文本响应内容：")
            print(response.text[:200])  # 防止输出过长
            return response.text
            
    except requests.exceptions.HTTPError as http_err:
        print(f"HTTP 错误: {http_err}")
    except requests.exceptions.ConnectionError:
        print("连接错误：请检查网络连接或 URL")
    except requests.exceptions.Timeout:
        print("请求超时：请尝试增大 timeout 值")
    except requests.exceptions.RequestException as err:
        print(f"请求异常: {err}")
    except ValueError as json_err:  # JSON 解析错误
        print(f"JSON 解析错误: {json_err}")
    
    return None

if __name__ == "__main__":
    # 示例 API（可替换为您需要请求的 URL）
    test_url = "https://www.baidu.com"
    
    # 调用函数获取数据
    result = fetch_url(test_url)
    
    # 可添加后续处理逻辑
    if result:
        # 示例：提取并展示特定字段
        if isinstance(result, dict):
            print("\n提取的字段：")
            print(f"标题: {result.get('title', '')}")
            print(f"内容: {result.get('body', '')[:50]}...")